package _66PlusOne;

public class CSolution {

    public static void main(String[] args) {
        System.out.println("aa");
        System.out.println(plusOne(new int[]{1, 2, 9}));
        System.out.println(plusOne(new int[]{4, 9, 9, 9}));
        System.out.println(plusOne(new int[]{9, 9, 9, 9}));
    }

    private static int[] plusOne(int[] digits) {
        if (digits == null || digits.length == 0 || digits.length == 1 && digits[0] == 0) {
            return new int[]{1};
        }

        int factor = 1;
        for (int i = digits.length - 1; i >= 0; i--) {
            int result = digits[i] + factor;
            if (result <= 9) {
                digits[i] = result;
                return digits;
            }
            digits[i] = result % 10;
            factor = result / 10;
        }
        if (factor != 0) {
            int[] result = new int[digits.length + 1];
            result[0] = factor;
            for (int i = 1; i < result.length; i++) {
                result[i] = digits[i - 1];
            }
            return result;
        }
        return digits;
    }
}
